package com.naughty.shopapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.naughty.shopapi.mapper.*;
import com.naughty.shopapi.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.naughty.shopapi.utils.JWTUtil.isExpiration;
import static com.naughty.shopapi.utils.OrderFlake.get0rderNO;

@Api(tags = "订单相关操作")
@RestController
@RequestMapping("api")
public class OrdersController {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    /**
     * 订单预览数据， 从购物车进入预览，在预览中提交订单
     *
     * @return
     */
    @ApiOperation("用户订单预览数据")
    @GetMapping("/orders/preview")
    public ResponseEntity<Object> ordersPreview() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                final Integer userId = isToken.get(0).getId();
                final QueryWrapper<Address> wrapperAddressList = new QueryWrapper<>();
                wrapperAddressList.eq("user_id", userId);
                final List<Address> addressList = addressMapper.selectList(wrapperAddressList);
                final OrderPreviewVO orderPreviewVO = new OrderPreviewVO();
                //Cart---------------------------
                List<CartVO> CartOUT = new ArrayList<>();
                final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                wrapperCart.eq("user_id", isToken.get(0).getId())
                        .eq("is_checked", 1);
                List<Cart> objCart = cartMapper.selectList(wrapperCart);
                for (int i = 0; i < objCart.size(); i++) {
                    final CartVO cartVO = new CartVO();
                    final Goods goods = new Goods();
                    cartVO.setId(objCart.get(i).getId());
                    cartVO.setUser_id(objCart.get(i).getUser_id());
                    cartVO.setGoods_id(objCart.get(i).getGoods_id());
                    cartVO.setNum(objCart.get(i).getNum());
                    cartVO.setIs_checked(objCart.get(i).getIs_checked());

                    final QueryWrapper<Goods> wrapperGood = new QueryWrapper<>();
                    wrapperGood.eq("id", objCart.get(i).getGoods_id());
                    List<Goods> objGood = goodsMapper.selectList(wrapperGood);

                    goods.setId(objGood.get(0).getId());
                    goods.setUser_id(objGood.get(0).getUser_id());
                    goods.setCategory_id(objGood.get(0).getCategory_id());
                    goods.setTitle(objGood.get(0).getTitle());
                    goods.setDescription(objGood.get(0).getDescription());
                    goods.setPrice(objGood.get(0).getPrice());
                    goods.setStock(objGood.get(0).getStock());
                    goods.setSales(objGood.get(0).getSales());
                    goods.setCover(objGood.get(0).getCover());
                    goods.setPics(objGood.get(0).getPics());
                    goods.setIs_on(objGood.get(0).getIs_on());
                    goods.setIs_recommend(objGood.get(0).getIs_recommend());
                    goods.setDetails(objGood.get(0).getDetails());
                    goods.setCreated_at(objGood.get(0).getCreated_at());
                    goods.setUpdated_at(objGood.get(0).getUpdated_at());
                    goods.setCollects_count(objGood.get(0).getCollects_count());
                    goods.setCover_url(objGood.get(0).getCover_url());
                    goods.setPics_url(objGood.get(0).getPics_url());
                    goods.setIs_collect(objGood.get(0).getIs_collect());

                    cartVO.setGoods(goods);
                    cartVO.setCreated_at(objCart.get(i).getCreated_at());
                    cartVO.setUpdated_at(objCart.get(i).getUpdated_at());
                    CartOUT.add(cartVO);
                }

                orderPreviewVO.setAddress(addressList);
                orderPreviewVO.setCarts(CartOUT);
                return new ResponseEntity<>(orderPreviewVO, HttpStatus.OK);
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 提交订单，地址id非空
     *
     * @param address_id
     * @return
     */
    @ApiOperation("用户提交订单")
    @PostMapping("/orders")
    public ResponseEntity<Object> ordersSubmit(@RequestParam String address_id) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                //address非空，判断是否存在
                final RegisterErrors registerErrors = new RegisterErrors();
                final HashMap<String, Object> errormsg = new HashMap<>();
                final ArrayList<Object> addressMsg = new ArrayList<>();
                Boolean addressBoo = false;
                if (address_id == "") {//address_id 条件
                    addressMsg.add("收货地址 不能为空");
                    errormsg.put("address_id", addressMsg);
                } else {
                    final QueryWrapper<Address> wrapperAddress = new QueryWrapper<>();
                    wrapperAddress.eq("user_id", isToken.get(0).getId())
                            .eq("id", Integer.parseInt(String.valueOf(address_id)));
                    final List<Address> address = addressMapper.selectList(wrapperAddress);
                    if (address.size() == 0) {
                        addressMsg.add("address id 不存在");
                        errormsg.put("address_id", addressMsg);
                    } else {
                        addressBoo = true;
                    }
                }

                if (addressBoo) {
                    final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                    wrapperCart.eq("user_id", isToken.get(0).getId())
                            .eq("is_checked", 1);
                    List<Cart> objCart = cartMapper.selectList(wrapperCart);

                    int sumPrice = 0;
                    for (int i = 0; i < objCart.size(); i++) {
                        final QueryWrapper<Goods> wrapperGood = new QueryWrapper<>();
                        wrapperGood.eq("id", objCart.get(i).getGoods_id());
                        List<Goods> objGood = goodsMapper.selectList(wrapperGood);
                        sumPrice += objGood.get(0).getPrice() * objCart.get(i).getNum();//计算总价
                    }

                    final Orders orders = new Orders();
                    final String orderNo = get0rderNO();
                    orders.setUser_id(isToken.get(0).getId());
                    orders.setOrder_no(orderNo);
                    orders.setAmount(sumPrice);
                    orders.setAddress_id(Integer.parseInt(String.valueOf(address_id)));
                    orders.setStatus(1);
                    ordersMapper.insert(orders);//插入订单信息

                    final QueryWrapper<Orders> wrapperOrders = new QueryWrapper<>();
                    wrapperOrders.eq("user_id", isToken.get(0).getId());
                    wrapperOrders.eq("order_no", orderNo);
                    final List<Orders> ordersList = ordersMapper.selectList(wrapperOrders);
                    final Integer Oid = ordersList.get(0).getId();

                    for (int i = 0; i < objCart.size(); i++) {//利用购物车信息获取订单详情信息
                        final OrderDetails orderDetails = new OrderDetails();
                        final QueryWrapper<Goods> wrapperGood = new QueryWrapper<>();
                        wrapperGood.eq("id", objCart.get(i).getGoods_id());
                        List<Goods> objGood = goodsMapper.selectList(wrapperGood);

                        orderDetails.setGoods_id(objGood.get(0).getId());
                        orderDetails.setPrice(objGood.get(0).getPrice() * objCart.get(i).getNum());//每条购物车里的总价
                        orderDetails.setNum(objCart.get(i).getNum());
                        orderDetails.setOrder_id(Oid);
                        orderDetailsMapper.insert(orderDetails);//插入商品详情信息
                    }
                    cartMapper.delete(wrapperCart);//清除已选中的购物车

                    final List<Orders> ordersListRes = ordersMapper.selectList(wrapperOrders);
                    final Orders orderRes = new Orders();//对象返回
                    orderRes.setId(ordersListRes.get(0).getId());
                    orderRes.setOrder_no(ordersListRes.get(0).getOrder_no());
                    orderRes.setUser_id(ordersListRes.get(0).getUser_id());
                    orderRes.setAmount(ordersListRes.get(0).getAmount());
                    orderRes.setStatus(ordersListRes.get(0).getStatus());
                    orderRes.setAddress_id(ordersListRes.get(0).getAddress_id());
                    orderRes.setExpress_no(ordersListRes.get(0).getExpress_no());
                    orderRes.setExpress_type(ordersListRes.get(0).getExpress_type());
                    orderRes.setPay_time(ordersListRes.get(0).getPay_time());
                    orderRes.setPay_type(ordersListRes.get(0).getPay_type());
                    orderRes.setTrade_no(ordersListRes.get(0).getTrade_no());
                    orderRes.setCreated_at(ordersListRes.get(0).getCreated_at());
                    orderRes.setUpdated_at(ordersListRes.get(0).getUpdated_at());
                    return new ResponseEntity<>(orderRes, HttpStatus.OK);
                } else {
                    registerErrors.setMessage("The given data was invalid.");
                    registerErrors.setErrors(errormsg);
                    registerErrors.setStatus_code(422);
                    return new ResponseEntity<>(registerErrors, HttpStatus.UNPROCESSABLE_ENTITY);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 订单列表
     * <p>
     * include可以返回额外的数据， 多个使用 ， 分隔， 比如： include=goods,user，orderDetails
     * 多层关联可以是 . , 比如要获取订单细节的同时，还要获取细节关联的商品：include=orderDetails.goods
     * 推荐使用的方式： include=orderDetails.goods
     *
     * @param page    分页
     * @param title   标题模糊搜索
     * @param status  订单状态: 1下单 2支付 3发货 4收货 5过期
     * @param include 包含额外的数据： goods 商品，user 用户 ，orderDetails订单详情
     * @return
     */
    @ApiOperation("用户订单列表")
    @GetMapping("/orders")
    public ResponseEntity<Object> ordersList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(required = false) String title,
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(required = false) String include
    ) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                int pageAbs = 1;    //正负过滤
                int statusAbs = 1;
                if (page <= 1) {
                    pageAbs = 1;
                } else {
                    pageAbs = Math.abs(page);
                }
                if (status <= 1) {
                    statusAbs = 1;
                } else {
                    statusAbs = Math.abs(status);
                }
                final MetaListVO metaListVO = new MetaListVO();
                final MetaPaginationVO metaPaginationVO = new MetaPaginationVO();
                final Meta meta = new Meta();

                if (include == null) {//不存才include值
                    final QueryWrapper<Orders> wrapperOrders = new QueryWrapper<>();
                    wrapperOrders.eq("status", statusAbs);
                    wrapperOrders.eq("user_id", isToken.get(0).getId());
                    final Page<Orders> OrdersPage = new Page<>(pageAbs, 10);
                    ordersMapper.selectPage(OrdersPage, wrapperOrders);
                    final List<Orders> pageOrdersRecords = OrdersPage.getRecords();//拿到所有原版用户订单信息

                    final float pageCount = (float) OrdersPage.getTotal() / 10;
                    final double currentPageCount = Math.ceil(pageCount);
                    meta.setTotal(OrdersPage.getTotal()); //数据总数
                    meta.setCount(OrdersPage.getRecords().size());//当前页数据条数
                    meta.setPer_page(10);//每页数据条数
                    meta.setCurrent_page(pageAbs);//当前页码
                    meta.setTotal_pages((int) currentPageCount);//总页数CollectsPage.getTotal()|((long) floor < 1) ? 1 : (long) floor
                    if (currentPageCount <= 1) {
                        meta.setLinks(null);
                    } else {
                        String path = "http://localhost:8182/api/orders";
                        if (pageAbs <= currentPageCount) {
                            if (pageAbs == 1) {
                                final HashMap<String, Object> linkMap = new HashMap<>();
                                linkMap.put("previous", null);
                                linkMap.put("next", path + "?page=" + (pageAbs + 1));
                                meta.setLinks(linkMap);
                            } else {
                                if (pageAbs == currentPageCount) {
                                    final HashMap<String, Object> linkMap = new HashMap<>();
                                    linkMap.put("previous", path + "?page=" + (pageAbs - 1));
                                    linkMap.put("next", null);
                                    meta.setLinks(linkMap);
                                } else {
                                    final HashMap<String, Object> linkMap = new HashMap<>();
                                    linkMap.put("previous", path + "?page=" + (pageAbs - 1));
                                    linkMap.put("next", path + "?page=" + (pageAbs + 1));
                                    meta.setLinks(linkMap);
                                }
                            }
                        } else {
                            meta.setLinks(null);
                        }
                    }
                    metaPaginationVO.setPagination(meta);
                    metaListVO.setData(pageOrdersRecords);
                    metaListVO.setMeta(metaPaginationVO);
                    return new ResponseEntity<>(metaListVO, HttpStatus.OK);
                } else {//=======================================存在include值====================
                    final List<OrdersDetailsVO> ordersDetailsVOOut = new ArrayList<>();//所有订单外层

                    //获取该用户的所有订单---基本分页设置
                    final QueryWrapper<Orders> wrapperOrders = new QueryWrapper<>();//获取所有订单列表
                    wrapperOrders.eq("status", statusAbs);
                    wrapperOrders.eq("user_id", isToken.get(0).getId());
                    final Page<Orders> OrdersPage = new Page<>(pageAbs, 10);
                    ordersMapper.selectPage(OrdersPage, wrapperOrders);

                    final float pageCount = (float) OrdersPage.getTotal() / 10; //meta总控字段
                    final double currentPageCount = Math.ceil(pageCount);
                    meta.setTotal(OrdersPage.getTotal()); //数据总数
                    meta.setCount(OrdersPage.getRecords().size());//当前页数据条数
                    meta.setPer_page(10);//每页数据条数
                    meta.setCurrent_page(pageAbs);//当前页码
                    meta.setTotal_pages((int) currentPageCount);//总页数CollectsPage.getTotal()|((long) floor < 1) ? 1 : (long) floor
                    if (currentPageCount <= 1) {
                        meta.setLinks(null);
                    } else {
                        String path = "http://localhost:8182/api/orders";
                        if (pageAbs <= currentPageCount) {
                            if (pageAbs == 1) {
                                final HashMap<String, Object> linkMap = new HashMap<>();
                                linkMap.put("previous", null);
                                linkMap.put("next", path + "?page=" + (pageAbs + 1));
                                meta.setLinks(linkMap);
                            } else {
                                if (pageAbs == currentPageCount) {
                                    final HashMap<String, Object> linkMap = new HashMap<>();
                                    linkMap.put("previous", path + "?page=" + (pageAbs - 1));
                                    linkMap.put("next", null);
                                    meta.setLinks(linkMap);
                                } else {
                                    final HashMap<String, Object> linkMap = new HashMap<>();
                                    linkMap.put("previous", path + "?page=" + (pageAbs - 1));
                                    linkMap.put("next", path + "?page=" + (pageAbs + 1));
                                    meta.setLinks(linkMap);
                                }
                            }
                        } else {
                            meta.setLinks(null);
                        }
                    }

                    //分割include值--匹配对应字段，做出相应的对象返回
                    final String[] includeSplit = include.split(",");
                    System.out.println(includeSplit.length);
                    if (includeSplit.length == 1) {
                        for (String s : includeSplit) {
                            if (s.equals("orderDetails")) {//当include == orderDetails
                                for (int i = 0; i < OrdersPage.getRecords().size(); i++) {
                                    final OrdersDetailsVO ordersDetailsVO = new OrdersDetailsVO();
                                    final HashMap<String, Object> dataMap = new HashMap<>();

                                    ordersDetailsVO.setId(OrdersPage.getRecords().get(i).getId());
                                    ordersDetailsVO.setUser_id(OrdersPage.getRecords().get(i).getUser_id());
                                    ordersDetailsVO.setOrder_no(OrdersPage.getRecords().get(i).getOrder_no());
                                    ordersDetailsVO.setAmount(OrdersPage.getRecords().get(i).getAmount());
                                    ordersDetailsVO.setAddress_id(OrdersPage.getRecords().get(i).getAddress_id());
                                    ordersDetailsVO.setStatus(OrdersPage.getRecords().get(i).getStatus());
                                    ordersDetailsVO.setExpress_no(OrdersPage.getRecords().get(i).getExpress_no());
                                    ordersDetailsVO.setExpress_type(OrdersPage.getRecords().get(i).getExpress_type());
                                    ordersDetailsVO.setPay_type(OrdersPage.getRecords().get(i).getPay_type());
                                    ordersDetailsVO.setPay_time(OrdersPage.getRecords().get(i).getPay_time());
                                    ordersDetailsVO.setTrade_no(OrdersPage.getRecords().get(i).getTrade_no());
                                    ordersDetailsVO.setCreated_at(OrdersPage.getRecords().get(i).getCreated_at());
                                    ordersDetailsVO.setUpdated_at(OrdersPage.getRecords().get(i).getUpdated_at());

                                    final QueryWrapper<OrderDetails> wrapperOrderDetails = new QueryWrapper<>();
                                    wrapperOrderDetails.eq("order_id", OrdersPage.getRecords().get(i).getId());
                                    final List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(wrapperOrderDetails);

                                    dataMap.put("data", orderDetailsList);

                                    ordersDetailsVO.setOrderDetails(dataMap);
                                    ordersDetailsVOOut.add(ordersDetailsVO);
                                }

                                metaPaginationVO.setPagination(meta);
                                metaListVO.setData(ordersDetailsVOOut);
                                metaListVO.setMeta(metaPaginationVO);
                            }
                            if (s.equals("user")) {
                                for (int i = 0; i < OrdersPage.getRecords().size(); i++) {
                                    final OrdersDetailsVO ordersDetailsVO = new OrdersDetailsVO();
                                    final HashMap<String, Object> dataMap = new HashMap<>();

                                    ordersDetailsVO.setId(OrdersPage.getRecords().get(i).getId());
                                    ordersDetailsVO.setUser_id(OrdersPage.getRecords().get(i).getUser_id());
                                    ordersDetailsVO.setOrder_no(OrdersPage.getRecords().get(i).getOrder_no());
                                    ordersDetailsVO.setAmount(OrdersPage.getRecords().get(i).getAmount());
                                    ordersDetailsVO.setAddress_id(OrdersPage.getRecords().get(i).getAddress_id());
                                    ordersDetailsVO.setStatus(OrdersPage.getRecords().get(i).getStatus());
                                    ordersDetailsVO.setExpress_no(OrdersPage.getRecords().get(i).getExpress_no());
                                    ordersDetailsVO.setExpress_type(OrdersPage.getRecords().get(i).getExpress_type());
                                    ordersDetailsVO.setPay_type(OrdersPage.getRecords().get(i).getPay_type());
                                    ordersDetailsVO.setPay_time(OrdersPage.getRecords().get(i).getPay_time());
                                    ordersDetailsVO.setTrade_no(OrdersPage.getRecords().get(i).getTrade_no());
                                    ordersDetailsVO.setCreated_at(OrdersPage.getRecords().get(i).getCreated_at());
                                    ordersDetailsVO.setUpdated_at(OrdersPage.getRecords().get(i).getUpdated_at());

                                    final QueryWrapper<Users> wrapperUsers = new QueryWrapper<>();
                                    wrapperUsers.eq("id", OrdersPage.getRecords().get(i).getUser_id());
                                    final List<Users> UsersInfoList = usersMapper.selectList(wrapperUsers);

                                    final Users users = new Users();
                                    users.setId(UsersInfoList.get(0).getId());
                                    users.setName(UsersInfoList.get(0).getName());
                                    users.setEmail(UsersInfoList.get(0).getEmail());
                                    users.setPhone(UsersInfoList.get(0).getPhone());
                                    users.setAvatar(UsersInfoList.get(0).getAvatar());
                                    users.setOpenid(UsersInfoList.get(0).getOpenid());
                                    users.setAvatar_url(UsersInfoList.get(0).getAvatar_url());
                                    users.setIs_locked(UsersInfoList.get(0).getIs_locked());
                                    users.setCreated_at(UsersInfoList.get(0).getCreated_at());
                                    users.setUpdated_at(UsersInfoList.get(0).getUpdated_at());

                                    ordersDetailsVO.setUser(users);
                                    ordersDetailsVOOut.add(ordersDetailsVO);
                                }

                                metaPaginationVO.setPagination(meta);
                                metaListVO.setData(ordersDetailsVOOut);
                                metaListVO.setMeta(metaPaginationVO);
                            }
                            if (s.equals("goods")) {//当include == goods
                                for (int i = 0; i < OrdersPage.getRecords().size(); i++) {
                                    final OrdersDetailsVO ordersDetailsVO = new OrdersDetailsVO();
                                    final HashMap<String, Object> dataMap = new HashMap<>();
                                    final List<Object> goodsListOut = new ArrayList<>();//放置所有商品

                                    ordersDetailsVO.setId(OrdersPage.getRecords().get(i).getId());
                                    ordersDetailsVO.setUser_id(OrdersPage.getRecords().get(i).getUser_id());
                                    ordersDetailsVO.setOrder_no(OrdersPage.getRecords().get(i).getOrder_no());
                                    ordersDetailsVO.setAmount(OrdersPage.getRecords().get(i).getAmount());
                                    ordersDetailsVO.setAddress_id(OrdersPage.getRecords().get(i).getAddress_id());
                                    ordersDetailsVO.setStatus(OrdersPage.getRecords().get(i).getStatus());
                                    ordersDetailsVO.setExpress_no(OrdersPage.getRecords().get(i).getExpress_no());
                                    ordersDetailsVO.setExpress_type(OrdersPage.getRecords().get(i).getExpress_type());
                                    ordersDetailsVO.setPay_type(OrdersPage.getRecords().get(i).getPay_type());
                                    ordersDetailsVO.setPay_time(OrdersPage.getRecords().get(i).getPay_time());
                                    ordersDetailsVO.setTrade_no(OrdersPage.getRecords().get(i).getTrade_no());
                                    ordersDetailsVO.setCreated_at(OrdersPage.getRecords().get(i).getCreated_at());
                                    ordersDetailsVO.setUpdated_at(OrdersPage.getRecords().get(i).getUpdated_at());

                                    final QueryWrapper<OrderDetails> wrapperOrderDetails = new QueryWrapper<>();
                                    wrapperOrderDetails.eq("order_id", OrdersPage.getRecords().get(i).getId());
                                    final List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(wrapperOrderDetails);//获取所有订单详情列

                                    int j = 0;
                                    while (j < orderDetailsList.size()) {
                                        final Goods goods = new Goods();

                                        final QueryWrapper<Goods> wrapperGoods = new QueryWrapper<>();
                                        if (title != null) {//当title不为空时条件赋值
                                            wrapperGoods.like("title", title);//由于goods
                                            final Integer goods_id = orderDetailsList.get(j).getGoods_id();
                                            wrapperGoods.eq("id", goods_id);
                                        } else {
                                            final Integer goods_id = orderDetailsList.get(j).getGoods_id();
                                            wrapperGoods.eq("id", goods_id);
                                        }
                                        List<Goods> goodsList = goodsMapper.selectList(wrapperGoods);
                                        if (goodsList.size() == 0) {
                                            j++;
                                        } else {
                                            goods.setId(goodsList.get(0).getId());
                                            goods.setUser_id(goodsList.get(0).getUser_id());
                                            goods.setCategory_id(goodsList.get(0).getCategory_id());
                                            goods.setTitle(goodsList.get(0).getTitle());
                                            goods.setDescription(goodsList.get(0).getDescription());
                                            goods.setPrice(goodsList.get(0).getPrice());
                                            goods.setStock(goodsList.get(0).getStock());
                                            goods.setSales(goodsList.get(0).getSales());
                                            goods.setCover(goodsList.get(0).getCover());
                                            goods.setPics(goodsList.get(0).getPics());
                                            goods.setIs_on(goodsList.get(0).getIs_on());
                                            goods.setIs_recommend(goodsList.get(0).getIs_recommend());
                                            goods.setDetails(goodsList.get(0).getDetails());
                                            goods.setCreated_at(goodsList.get(0).getCreated_at());
                                            goods.setUpdated_at(goodsList.get(0).getUpdated_at());
                                            goods.setCollects_count(goodsList.get(0).getCollects_count());
                                            goods.setCover_url(goodsList.get(0).getCover_url());
                                            goods.setPics_url(goodsList.get(0).getPics_url());
                                            goods.setIs_collect(goodsList.get(0).getIs_collect());

                                            goodsListOut.add(goods);
                                            j++;
                                        }

                                    }

                                    dataMap.put("data", goodsListOut);

                                    ordersDetailsVO.setGoods(dataMap);

                                    ordersDetailsVOOut.add(ordersDetailsVO);
                                }

                                metaPaginationVO.setPagination(meta);
                                metaListVO.setData(ordersDetailsVOOut);
                                metaListVO.setMeta(metaPaginationVO);

                            }
                            if (s.equals("orderDetails.goods")) {
                                for (int i = 0; i < OrdersPage.getRecords().size(); i++) {
                                    final OrdersDetailsVO ordersDetailsVO = new OrdersDetailsVO();
                                    final HashMap<String, Object> dataMap = new HashMap<>();
                                    final List<Object> orderDetailsListOut = new ArrayList<>();//放置所有商品
                                    //最外层订单的信息
                                    ordersDetailsVO.setId(OrdersPage.getRecords().get(i).getId());
                                    ordersDetailsVO.setUser_id(OrdersPage.getRecords().get(i).getUser_id());
                                    ordersDetailsVO.setOrder_no(OrdersPage.getRecords().get(i).getOrder_no());
                                    ordersDetailsVO.setAmount(OrdersPage.getRecords().get(i).getAmount());
                                    ordersDetailsVO.setAddress_id(OrdersPage.getRecords().get(i).getAddress_id());
                                    ordersDetailsVO.setStatus(OrdersPage.getRecords().get(i).getStatus());
                                    ordersDetailsVO.setExpress_no(OrdersPage.getRecords().get(i).getExpress_no());
                                    ordersDetailsVO.setExpress_type(OrdersPage.getRecords().get(i).getExpress_type());
                                    ordersDetailsVO.setPay_type(OrdersPage.getRecords().get(i).getPay_type());
                                    ordersDetailsVO.setPay_time(OrdersPage.getRecords().get(i).getPay_time());
                                    ordersDetailsVO.setTrade_no(OrdersPage.getRecords().get(i).getTrade_no());
                                    ordersDetailsVO.setCreated_at(OrdersPage.getRecords().get(i).getCreated_at());
                                    ordersDetailsVO.setUpdated_at(OrdersPage.getRecords().get(i).getUpdated_at());

                                    //查询对应订单的id的详细订单信息
                                    final QueryWrapper<OrderDetails> wrapperOrderDetails = new QueryWrapper<>();
                                    wrapperOrderDetails.eq("order_id", OrdersPage.getRecords().get(i).getId());
                                    final List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(wrapperOrderDetails);
                                    /**
                                     * 因为同一订单id中可能对应比自身数量还多的详细订单列，采用while循环
                                     * 循环比自身范围大的列，当对应订单id中所有的详细订单全部循环完毕，赋值完成，再进入下一循环
                                     */
                                    int j = 0;
                                    while (j < orderDetailsList.size()) {
                                        final Goods goods = new Goods();
                                        final OrdersDetailsGoodsVO ordersDetailsGoodsVO = new OrdersDetailsGoodsVO();

                                        //获取详细订单中的信息
                                        ordersDetailsGoodsVO.setId(orderDetailsList.get(j).getId());
                                        ordersDetailsGoodsVO.setOrder_id(orderDetailsList.get(j).getOrder_id());
                                        ordersDetailsGoodsVO.setGoods_id(orderDetailsList.get(j).getGoods_id());
                                        ordersDetailsGoodsVO.setPrice(orderDetailsList.get(j).getPrice());
                                        ordersDetailsGoodsVO.setNum(orderDetailsList.get(j).getNum());
                                        ordersDetailsGoodsVO.setCreated_at(orderDetailsList.get(j).getCreated_at());
                                        ordersDetailsGoodsVO.setUpdated_at(orderDetailsList.get(j).getUpdated_at());

                                        //获取详细订单中对应的商品信息，加入到详细订单中的goods字段--条件构造
                                        final QueryWrapper<Goods> wrapperGoods = new QueryWrapper<>();
                                        if (title != null) {//当title不为空时条件赋值
                                            wrapperGoods.like("title", title);//由于goods
                                            final Integer goods_id = orderDetailsList.get(j).getGoods_id();
                                            wrapperGoods.eq("id", goods_id);
                                        } else {
                                            final Integer goods_id = orderDetailsList.get(j).getGoods_id();
                                            wrapperGoods.eq("id", goods_id);
                                        }
                                        List<Goods> goodsList = goodsMapper.selectList(wrapperGoods);
                                        if (goodsList.size() == 0) {//结合判断title变量值
                                            j++;
                                            ordersDetailsGoodsVO.setGoods(null);
                                        } else {
                                            goods.setId(goodsList.get(0).getId());
                                            goods.setUser_id(goodsList.get(0).getUser_id());
                                            goods.setCategory_id(goodsList.get(0).getCategory_id());
                                            goods.setTitle(goodsList.get(0).getTitle());
                                            goods.setDescription(goodsList.get(0).getDescription());
                                            goods.setPrice(goodsList.get(0).getPrice());
                                            goods.setStock(goodsList.get(0).getStock());
                                            goods.setSales(goodsList.get(0).getSales());
                                            goods.setCover(goodsList.get(0).getCover());
                                            goods.setPics(goodsList.get(0).getPics());
                                            goods.setIs_on(goodsList.get(0).getIs_on());
                                            goods.setIs_recommend(goodsList.get(0).getIs_recommend());
                                            goods.setDetails(goodsList.get(0).getDetails());
                                            goods.setCreated_at(goodsList.get(0).getCreated_at());
                                            goods.setUpdated_at(goodsList.get(0).getUpdated_at());
                                            goods.setCollects_count(goodsList.get(0).getCollects_count());
                                            goods.setCover_url(goodsList.get(0).getCover_url());
                                            goods.setPics_url(goodsList.get(0).getPics_url());
                                            goods.setIs_collect(goodsList.get(0).getIs_collect());

                                            ordersDetailsGoodsVO.setGoods(goods);
                                            j++;
                                        }
                                        orderDetailsListOut.add(ordersDetailsGoodsVO);
                                    }
                                    dataMap.put("data", orderDetailsListOut);
                                    ordersDetailsVO.setOrderDetails(dataMap);
                                    ordersDetailsVOOut.add(ordersDetailsVO);
                                }
                                metaListVO.setData(ordersDetailsVOOut);
                                metaPaginationVO.setPagination(meta);
                                metaListVO.setMeta(metaPaginationVO);
                            }
                        }
                    } else {
                        if ((include.equals("orderDetails,goods")) || (include.equals("goods,orderDetails"))) {
                            for (int i = 0; i < OrdersPage.getRecords().size(); i++) {
                                final OrdersDetailsVO ordersDetailsVO = new OrdersDetailsVO();
                                final HashMap<String, Object> dataMapOrderDetail = new HashMap<>();
                                final HashMap<String, Object> dataMapGoodList = new HashMap<>();
                                final List<Object> goodsListOut = new ArrayList<>();//放置所有商品

                                ordersDetailsVO.setId(OrdersPage.getRecords().get(i).getId());
                                ordersDetailsVO.setUser_id(OrdersPage.getRecords().get(i).getUser_id());
                                ordersDetailsVO.setOrder_no(OrdersPage.getRecords().get(i).getOrder_no());
                                ordersDetailsVO.setAmount(OrdersPage.getRecords().get(i).getAmount());
                                ordersDetailsVO.setAddress_id(OrdersPage.getRecords().get(i).getAddress_id());
                                ordersDetailsVO.setStatus(OrdersPage.getRecords().get(i).getStatus());
                                ordersDetailsVO.setExpress_no(OrdersPage.getRecords().get(i).getExpress_no());
                                ordersDetailsVO.setExpress_type(OrdersPage.getRecords().get(i).getExpress_type());
                                ordersDetailsVO.setPay_type(OrdersPage.getRecords().get(i).getPay_type());
                                ordersDetailsVO.setPay_time(OrdersPage.getRecords().get(i).getPay_time());
                                ordersDetailsVO.setTrade_no(OrdersPage.getRecords().get(i).getTrade_no());
                                ordersDetailsVO.setCreated_at(OrdersPage.getRecords().get(i).getCreated_at());
                                ordersDetailsVO.setUpdated_at(OrdersPage.getRecords().get(i).getUpdated_at());

                                final QueryWrapper<OrderDetails> wrapperOrderDetails = new QueryWrapper<>();
                                wrapperOrderDetails.eq("order_id", OrdersPage.getRecords().get(i).getId());
                                final List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(wrapperOrderDetails);

                                dataMapOrderDetail.put("data", orderDetailsList);

                                ordersDetailsVO.setOrderDetails(dataMapOrderDetail);


                                ////-------------------goodsList-------------------/////

                                int j = 0;
                                while (j < orderDetailsList.size()) {
                                    final Goods goods = new Goods();

                                    final QueryWrapper<Goods> wrapperGoods = new QueryWrapper<>();
                                    if (title != null) {//当title不为空时条件赋值
                                        wrapperGoods.like("title", title);//由于goods
                                        final Integer goods_id = orderDetailsList.get(j).getGoods_id();
                                        wrapperGoods.eq("id", goods_id);
                                    } else {
                                        final Integer goods_id = orderDetailsList.get(j).getGoods_id();
                                        wrapperGoods.eq("id", goods_id);
                                    }
                                    List<Goods> goodsList = goodsMapper.selectList(wrapperGoods);
                                    if (goodsList.size() == 0) {
                                        j++;
                                    } else {
                                        goods.setId(goodsList.get(0).getId());
                                        goods.setUser_id(goodsList.get(0).getUser_id());
                                        goods.setCategory_id(goodsList.get(0).getCategory_id());
                                        goods.setTitle(goodsList.get(0).getTitle());
                                        goods.setDescription(goodsList.get(0).getDescription());
                                        goods.setPrice(goodsList.get(0).getPrice());
                                        goods.setStock(goodsList.get(0).getStock());
                                        goods.setSales(goodsList.get(0).getSales());
                                        goods.setCover(goodsList.get(0).getCover());
                                        goods.setPics(goodsList.get(0).getPics());
                                        goods.setIs_on(goodsList.get(0).getIs_on());
                                        goods.setIs_recommend(goodsList.get(0).getIs_recommend());
                                        goods.setDetails(goodsList.get(0).getDetails());
                                        goods.setCreated_at(goodsList.get(0).getCreated_at());
                                        goods.setUpdated_at(goodsList.get(0).getUpdated_at());
                                        goods.setCollects_count(goodsList.get(0).getCollects_count());
                                        goods.setCover_url(goodsList.get(0).getCover_url());
                                        goods.setPics_url(goodsList.get(0).getPics_url());
                                        goods.setIs_collect(goodsList.get(0).getIs_collect());

                                        goodsListOut.add(goods);
                                        j++;
                                    }

                                }

                                dataMapGoodList.put("data", goodsListOut);

                                ordersDetailsVO.setGoods(dataMapGoodList);

                                ordersDetailsVOOut.add(ordersDetailsVO);
                            }
                            metaPaginationVO.setPagination(meta);
                            metaListVO.setData(ordersDetailsVOOut);
                            metaListVO.setMeta(metaPaginationVO);
                        }
                    }
                    return new ResponseEntity<>(metaListVO, HttpStatus.OK);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }
}
